package com.link.base.wechat.common.util;

import com.alibaba.fastjson.JSONObject;
import com.link.base.wechat.basic.util.WxExceptionUtil;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.HttpRequestUtil;
import com.link.core.util.StringUtils;

/**
 * 微信二维码工具
 *
 * @author ouyangzhenqiang
 * @date 2019/02/28 19:28
 */
public class WxQRCodeUtil {

    /**
     * 创建临时二维码ticket及链接
     *
     * @author ouyangzhenqiang
     * @date 2019/02/28 19:28
     * @param access_token 接口调用凭证
     * @param scene_id 开发者自行设定的参数（scene_id）
     * @param time 临时二维码的有效时间
     */
    public static JSONObject createTempQrCode(String access_token, String scene_id, String time) throws Exception {
        if (StringUtils.isBlank(access_token)) {
            throw new ServiceException("WXCOMMON-002");
        }
        if (StringUtils.isBlank(scene_id)) {
            throw new ServiceException("WXCOMMON-003");
        }
        if (StringUtils.isBlank(time)) {
            throw new ServiceException("WXCOMMON-004");
        }
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;
        String param = "{\"expire_seconds\": " + time
            + ", \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + scene_id + "}}}";
        String result = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(result);
    }

    /**
     * 创建永久二维码ticket及链接
     *
     * @author ouyangzhenqiang
     * @date 2019/02/28 19:28
     * @param access_token 接口调用凭证
     * @param scene_str 开发者自行设定的参数（scene_str）
     */
    public static JSONObject createForeverQrCode(String access_token, String scene_str) throws Exception {
        if (StringUtils.isBlank(access_token)) {
            throw new ServiceException("WXCOMMON-002");
        }
        if (StringUtils.isBlank(scene_str)) {
            throw new ServiceException("WXCOMMON-005");
        }
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;
        String param = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + scene_str + "\"}}}";
        String result = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(result);
    }

    /**
     * 根据ticket直接获取二维码url
     * 
     * @author ouyangzhenqiang
     * @date 2019/03/14 20:53
     * @param ticket ticket
     */
    public static String getWxQrCodeUrlByTicket(String ticket) throws Exception {
        if (StringUtils.isBlank(ticket)) {
            throw new ServiceException("WXCOMMON-006");
        }
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + StringUtils.urlEncoder(ticket, "UTF-8");
    }

}
